package com.bangbang.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.bangbang.config.AlipayConfig;
import com.bangbang.configresult.Result;
import com.bangbang.configresult.ResultEnum;
import com.bangbang.dto.TbGroupCourseOrderDTO;
import com.bangbang.pojo.AlipayBaseBean;
import com.bangbang.pojo.AlipayBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("alipay")
public class AlipayController {

    @Autowired
    private AlipayClient alipayClient;

    @ApiOperation(value = "支付服务")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "课程订单号",name = "orderNumber",required = true, paramType = "query"),
            @ApiImplicitParam(value = "课程价格",name = "price",required = true, paramType = "query"),
            @ApiImplicitParam(value = "课程订单信息",name = "subject",required = false, paramType = "query"),
            @ApiImplicitParam(value = "课程主体",name = "body",required = false, paramType = "query")
    })
    @PostMapping("alipayTradePagePay")
    @ResponseBody
    public String alipayTradePagePay(@RequestParam("orderNumber") Long orderNumber,@RequestParam("price") BigDecimal price,@RequestParam("subject") String subject,@RequestParam("body") String body){
        //获得初始化的AlipayClient
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //付款金额，必填
        //订单名称，必填
        //商品描述，可空

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ orderNumber +"\","
                + "\"total_amount\":\""+ price +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求 (执行玩后返回的字符串)
        String result = null;
        try {
             result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }

        return result;
    }
    //订单查询

    /**
     *
     * @param out_trade_no 商家订单号，平台订单号
     * @param trade_no 流水号
     * @return
     * @throws Exception
     */
    @ApiOperation("查询订单")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "订单号",name = "out_trade_no",required = true,paramType = "query"),
            @ApiImplicitParam(value = "贸易号（流水号）",name = "trade_no",required = true,paramType = "query")
    })
    @PostMapping("alipayTrandQuery")
    @ResponseBody
    public Result alipayTrandQuery(String out_trade_no, String trade_no) throws Exception {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

        //商户订单号，商户网站订单系统中唯一订单号
        //支付宝交易号
        //请二选一设置
        Map<String,Object> map = new HashMap<>();
        map.put("out_trade_no",out_trade_no);
        map.put("trade_no",trade_no);
        alipayRequest.setBizContent(JSONObject.toJSONString(map));
        System.err.println("交易号"+out_trade_no);
        System.err.println("贸易号"+trade_no);
        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        AlipayBean alipayBeans = JSONObject.parseObject(result, AlipayBean.class);
        String sign = alipayBeans.getSign();
        AlipayBaseBean query = alipayBeans.getAlipay_trade_query_response();
        System.err.println(query.getCode());
        System.err.println(query.getMsg());
        System.err.println(query.getTrade_amount());
        System.err.println(query.getTrade_status());
        System.err.println(query.getTrade_no());

        //输出
        return Result.buildResult(ResultEnum.SUCCESS).setResult(map);
    }

    /**
     *
     *         //请二选一设置
     *         //支付宝交易号
     * @param out_trade_no
     *         //商户订单号，商户网站订单系统中唯一订单号
     * @param trade_no
     *         //需要退款的金额，该金额不能大于订单金额，必填
     * @param refund_amount
     *         //退款的原因说明
     * @param refund_reason
     *         //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
     * @param out_request_no
     * @return
     */
    @ApiOperation("退款")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "out_trade_no",value = "订单号",required = true,paramType = "query"),
            @ApiImplicitParam(name = "trade_no",value = "商户订单号",required = true,paramType = "query"),
            @ApiImplicitParam(name = "refund_amount",value = "退款金额",required = true,paramType = "query"),
            @ApiImplicitParam(name = "refund_reason",value = "退款原因",required = true,paramType = "query"),
            @ApiImplicitParam(name = "out_request_no",value = "唯一标识标识一次退款请求，同一笔交易下退款此参数保持一致 （如果要部分退款，则必填）",required = true,paramType = "query")
    })
    @PostMapping("alipayTrandRefund")
    @ResponseBody
    public Result alipayTrandRefund(String out_trade_no ,String trade_no,String refund_amount, String refund_reason, String out_request_no){
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();



        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"trade_no\":\""+ trade_no +"\","
                + "\"refund_amount\":\""+ refund_amount +"\","
                + "\"refund_reason\":\""+ refund_reason +"\","
                + "\"out_request_no\":\""+ out_request_no +"\"}");

        //请求
        String result = null;
        try {
            result = alipayClient.execute(alipayRequest).getBody();
            //ToDO 在这里修改订单状态
            System.err.println(result);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //输出
        Map<String,Object> map = new HashMap<>();
        map.put("out_trade_no",out_trade_no);
        map.put("trade_no",trade_no);
        map.put("refund_amount",refund_amount);
        map.put("refund_reason",refund_reason);
        map.put("out_request_no",out_request_no);

        return Result.buildResult(ResultEnum.SUCCESS).setResult(map);
    }
}
